package com.mikgonz.farkle.ui;

import java.sql.SQLException;
import java.util.ArrayList;

import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;

import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;
import com.j256.ormlite.dao.CloseableIterator;
import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.IntentAction;
import com.mikgonz.farkle.AsyncRPC;
import com.mikgonz.farkle.PushNotifReceiver;
import com.mikgonz.farkle.R;
import com.mikgonz.farkle.Util;
import com.mikgonz.farkle.database.DatabaseOpenHelper;
import com.mikgonz.farkle.database.Message;
import com.mikgonz.farkle.shared.FarkleRequestFactory;

public class ChatActivity extends OrmLiteBaseActivity<DatabaseOpenHelper> {

	public static final String FRIEND = "friend";
	public static final String FRIEND_ID = "friendid";
	public static final String FROM = "from";
	public static final String BODY = "body";

	private String playerName;
	private String playerId;
	private String friend;
	private String friendId;
	private BroadcastReceiver myReceiver;
	private ListView messagesList;
	private EditText userInput;
	private MyAdapter mAdapter;
	private SharedPreferences prefs;
	private DatabaseOpenHelper helper;
	private ActionBar bar;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chat);

		prefs = PreferenceManager.getDefaultSharedPreferences(this);

		playerName = prefs.getString(Util.PREF_USERNAME, null);
		playerId = prefs.getString(Util.PREF_USERID, null);

		messagesList = (ListView) findViewById(R.id.messages_list);
		userInput = (EditText) findViewById(R.id.edit_text);

		setupActionBar();

	}

	private void setupActionBar() {
		bar = (ActionBar) findViewById(R.id.actionbar);

		Intent restart = new Intent(this, Main.class);
		restart.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
				| Intent.FLAG_ACTIVITY_CLEAR_TOP);
		bar.setHomeAction(new IntentAction(this, restart, R.drawable.house));

	}

	@Override
	protected void onStart() {
		super.onStart();
		myReceiver = new ChatMSGReceiver();
		registerReceiver(myReceiver, new IntentFilter(
				FarkleRequestFactory.NEW_MSG_ACTION));
		helper = getHelper();

		Bundle extras = getIntent().getExtras();
		friend = extras.getString(FRIEND);
		friendId = extras.getString(FRIEND_ID);

		populateChat();
	}

	private void populateChat() {
		ArrayList<Message> messages = new ArrayList<Message>();
		CloseableIterator<Message> i = null;
		try {
			i = helper.getMessagesDao().closeableIterator();
		} catch (SQLException e) {

			e.printStackTrace();
		}

		if (i == null)
			return;

		Message m;
		while (i.hasNext()) {
			m = i.next();
			if (m.getChatter().equals(friend))
				messages.add(m);
		}

		mAdapter = new MyAdapter(this, messages);
		messagesList.setAdapter(mAdapter);
	}

	public void onSend(View v) {

		if (playerId == null)
			return;

		String body = userInput.getText().toString();
		if (body.length() == 0)
			return;
		userInput.setText("");

		AsyncRPC task = new AsyncRPC(ChatActivity.this);
		task.execute(AsyncRPC.SEND_MSG, playerId, friendId, body.toString());

		Message m = new Message(friend, playerName, body.toString());
		try {
			helper.getMessagesDao().create(m);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		mAdapter.addItem(m);
	}

	@Override
	public void onStop() {
		if (myReceiver != null)
			unregisterReceiver(myReceiver);

		super.onStop();
	}

	class ChatMSGReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
			nm.cancel(PushNotifReceiver.NOTIF_ID);

			String from = intent.getStringExtra(FROM);
			String body = intent.getStringExtra(BODY);

			if (from.equals(friend))
				mAdapter.addItem(new Message(from, from, body));
		}
	}
}
